package com.example.sunmiv1.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;

import androidx.core.content.ContextCompat;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.StatisticsVipAdapter;
import com.example.sunmiv1.base.BaseActivity;
import com.example.sunmiv1.entity.StatisticsVipBean;
import com.example.sunmiv1.utils.MathUtil;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.charting.animation.Easing;
import com.example.sunmiv1.utils.charting.charts.PieChart;
import com.example.sunmiv1.utils.charting.components.Legend;
import com.example.sunmiv1.utils.charting.data.Entry;
import com.example.sunmiv1.utils.charting.data.PieData;
import com.example.sunmiv1.utils.charting.data.PieDataSet;
import com.example.sunmiv1.utils.charting.data.PieEntry;
import com.example.sunmiv1.utils.charting.formatter.PercentFormatter;
import com.example.sunmiv1.utils.charting.highlight.Highlight;
import com.example.sunmiv1.utils.charting.listener.OnChartValueSelectedListener;
import com.example.sunmiv1.utils.charting.utils.ColorTemplate;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MemberStatisticsActivity extends BaseActivity {


    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.tv_member_activeStatistics)
    TextView tvMemberActiveStatistics;
    @BindView(R.id.tv_member_sleepStatistics)
    TextView tvMemberSleepStatistics;
    @BindView(R.id.tv_member_birthdayStatistics)
    TextView tvMemberBirthdayStatistics;
    @BindView(R.id.member_chart)
    PieChart memberChart;
    @BindView(R.id.member_statistics_listView)
    PullToRefreshListView memberStatisticsListView;
    @BindView(R.id.linear_member_statistics)
    LinearLayout linearMemberStatistics;
    @BindView(R.id.member_left)
    ImageView memberLeft;
    @BindView(R.id.member_right)
    ImageView memberRight;
    @BindView(R.id.member_title)
    TextView memberTitle;

    private Context context;
    private ACache aCache;
    private Intent intent;

    /**
     * 根據生日獲取會員信息
     */
    private int statisticsPage = 1;
    private int statisticsType = 1;
    private int statisticsIndex = 0;
    private StatisticsVipBean statisticsVipBean;
    private StatisticsVipAdapter statisticsVipAdapter;
    private List<StatisticsVipBean.DataBean.ListBean> statisticsList = new ArrayList<>();

    private LoadingDialog loadingDialog;

    private int flag = 1;
    private boolean first = true;

    @Override
    protected void initView() {
        setContentView(R.layout.activity_member_statistics);
        ButterKnife.bind(this);
        titleTitle.setText(R.string.memberAnalysisTitle);
        context = this;
        aCache = ACache.get(context);
    }

    @Override
    protected void initData() {
        changeStatistics(2);
        getActivityVip("");
        initColor();
    }

    @Override
    protected void initListener() {

        memberStatisticsListView.setOnItemClickListener((parent, view, position, id) -> {
            intent = new Intent(context, VipDetailsActivity.class);
            intent.putExtra("vid", statisticsList.get(position - 1).getId());
            startActivity(intent);
        });

        memberStatisticsListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                statisticsPage = 1;
                statisticsList.clear();
                setStatisticsVipAdapter();
                if (statisticsType == 1) {
                    getVipByBirth(statisticsIndex);
                } else {
                    getVipByMonth(entries.get(statisticsIndex).getLabel());
                }
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (statisticsType == 1) {
                    getVipByBirth(statisticsIndex);
                } else {
                    getVipByMonth(entries.get(statisticsIndex).getLabel());
                }
            }
        });
    }

    private void initChart() {


        memberChart.setUsePercentValues(true);
        memberChart.getDescription().setEnabled(false);
        memberChart.setExtraOffsets(5, 10, 5, 5);

        memberChart.setDragDecelerationFrictionCoef(0.95f);


        memberChart.setExtraOffsets(20.f, 0.f, 20.f, 0.f);

        memberChart.setDrawHoleEnabled(true);
        memberChart.setHoleColor(Color.WHITE);

        memberChart.setTransparentCircleColor(Color.WHITE);
        memberChart.setTransparentCircleAlpha(110);

        memberChart.setHoleRadius(40f);
        memberChart.setTransparentCircleRadius(45f);

        memberChart.setDrawCenterText(true);

        memberChart.setRotationAngle(0);
        // enable rotation of the memberChart by touch
        memberChart.setRotationEnabled(true);
        memberChart.setHighlightPerTapEnabled(true);

        memberChart.animateY(1400, Easing.EaseInOutQuad);
        memberChart.highlightValues(null);


        memberChart.setDrawEntryLabels(!memberChart.isDrawEntryLabelsEnabled());
        memberChart.setDrawHoleEnabled(false);

        memberChart.invalidate();
        setLegend();
    }

    private void initColor() {
        for (int c : ColorTemplate.VORDIPLOM_COLORS) {
            colors.add(c);
        }
        for (int c : ColorTemplate.JOYFUL_COLORS) {
            colors.add(c);
        }
        for (int c : ColorTemplate.COLORFUL_COLORS) {
            colors.add(c);
        }
        for (int c : ColorTemplate.LIBERTY_COLORS) {
            colors.add(c);
        }
        for (int c : ColorTemplate.PASTEL_COLORS) {
            colors.add(c);
        }
        colors.add(ColorTemplate.getHoloBlue());
        initChart();
    }

    @OnClick({R.id.title_back, R.id.tv_member_activeStatistics, R.id.tv_member_sleepStatistics, R.id.tv_member_birthdayStatistics,
            R.id.member_left, R.id.member_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.tv_member_activeStatistics:
                statisticsPage = 1;
                statisticsList.clear();
                setStatisticsVipAdapter();
                memberChart.setSelected(false);
                changeStatistics(2);
                getActivityVip("");
                break;
            case R.id.tv_member_sleepStatistics:
                statisticsPage = 1;
                statisticsList.clear();
                setStatisticsVipAdapter();
                memberChart.setSelected(false);
                changeStatistics(3);
                getActivityVip("1");
                break;
            case R.id.tv_member_birthdayStatistics:
                statisticsPage = 1;
                statisticsList.clear();
                setStatisticsVipAdapter();
                memberChart.setSelected(false);
                changeStatistics(1);
                getBirthVip();
                break;

            case R.id.member_left:
                switch (flag) {
                    case 2:
                        flag = 1;
                        memberTitle.setText(R.string.memberAnalysisTip1);
                        memberLeft.setVisibility(View.INVISIBLE);
                        statisticsPage = 1;
                        statisticsList.clear();
                        setStatisticsVipAdapter();
                        memberChart.setSelected(false);
                        changeStatistics(2);
                        getActivityVip("");
                        break;
                    case 3:
                        flag = 2;
                        memberTitle.setText(R.string.memberAnalysisTip);
                        memberRight.setVisibility(View.VISIBLE);
                        statisticsPage = 1;
                        statisticsList.clear();
                        setStatisticsVipAdapter();
                        memberChart.setSelected(false);
                        changeStatistics(3);
                        getActivityVip("1");
                        break;
                }
                break;
            case R.id.member_right:
                switch (flag) {
                    case 1:
                        flag = 2;
                        memberTitle.setText(R.string.memberAnalysisTip2);
                        memberLeft.setVisibility(View.VISIBLE);
                        statisticsPage = 1;
                        statisticsList.clear();
                        setStatisticsVipAdapter();
                        memberChart.setSelected(false);
                        changeStatistics(3);
                        getActivityVip("1");
                        break;
                    case 2:
                        flag = 3;
                        memberTitle.setText(R.string.birthday_statistics);
                        memberLeft.setVisibility(View.VISIBLE);
                        memberRight.setVisibility(View.INVISIBLE);
                        statisticsPage = 1;
                        statisticsList.clear();
                        setStatisticsVipAdapter();
                        memberChart.setSelected(false);
                        changeStatistics(1);
                        getBirthVip();
                        break;
                }
                break;
        }
    }


    /**
     * 獲取活躍會員數餅狀圖
     */
    private int allActivity = 0;

    ArrayList<Integer> colors = new ArrayList<>();
    ArrayList<PieEntry> entries = new ArrayList<>();

    private void getActivityVip(String type) {
        JSONObject json = new JSONObject();
        try {
            json.put("type", type);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(context, Common.GET_ACTIVITY_USER_BREAD, Tools.createParameterCode(json), new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                try {
                    JSONObject jsonObject = new JSONObject(text);
                    entries.clear();
                    if (jsonObject.getInt("status") == 1) {
                        allActivity = 0;
                        for (int i = 0; i < jsonObject.getJSONArray("data").length(); i++) {
                            JSONObject data = jsonObject.getJSONArray("data").getJSONObject(i);
                            allActivity += data.getInt("value") < 0 ? -data.getInt("value") : data.getInt("value");
                            entries.add(new PieEntry(data.getInt("value") < 0 ? -data.getInt("value") : data.getInt("value"), data.getString("name")));
                        }
                        if (first && entries.size() > 0) {
                            first = false;
                            getVipByMonth(entries.get(0).getLabel());
                        }
                        setEntries(entries, 2);

                    } else {
                        allActivity = 0;
                        setEntries(entries, 2);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {

            }
        });
    }

    /**
     * 獲取會員生日餅狀圖
     */
    private void getBirthVip() {
        HttpUtils.post(context, Common.GET_BIRTH_USER_BREAD, Tools.createParameterCode(new JSONObject()), new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                try {
                    JSONObject jsonObject = new JSONObject(text);
                    entries.clear();
                    if (jsonObject.getInt("status") == 1) {
                        allActivity = 0;
                        for (int i = 0; i < jsonObject.getJSONArray("data").length(); i++) {
                            JSONObject data = jsonObject.getJSONArray("data").getJSONObject(i);
                            allActivity += data.getInt("value") < 0 ? -data.getInt("value") : data.getInt("value");
                            entries.add(new PieEntry(data.getInt("value") < 0 ?
                                    -data.getInt("value") : data.getInt("value"), data.getString("name")));
                        }
                        setEntries(entries, 1);
                    } else {
                        allActivity = 0;
                        setEntries(entries, 1);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {

            }
        });
    }

    /**
     * 根據月份獲取會員信息
     */
    private void getVipByMonth(String monty) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("type", flag == 1 ? "" : "1");
            jsonObject.put("timestamp", monty);
            jsonObject.put("page", statisticsPage);
            jsonObject.put("pageSize", "20");
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(context, Common.GET_ACTIVE_USER_BY_MONTH, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    memberStatisticsListView.onRefreshComplete();
                    if (statisticsPage == 1) {
                        statisticsList.clear();
                        setStatisticsVipAdapter();
                    }
                    try {
                        JSONObject json = new JSONObject(text);
                        if (json.getInt("status") == 1 && json.getJSONObject("data").has("list")) {
                            statisticsVipBean = GsonUtils.JsonToBean(text, StatisticsVipBean.class);
                            statisticsList.addAll(statisticsVipBean.getData().getList());
                            setStatisticsVipAdapter();
                            statisticsPage++;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                @Override
                protected void onFailure(ResponseException e) {
                    memberStatisticsListView.onRefreshComplete();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根據生日獲取會員信息
     */

    private void getVipByBirth(int index) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("type", index == 0 ? 1 : (index == 1 ? 2 : "other"));
            jsonObject.put("page", statisticsPage);
            jsonObject.put("pageSize", "20");
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(context, Common.GET_ACTIVE_USER_BY_BIRTH, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    memberStatisticsListView.onRefreshComplete();
                    if (statisticsPage == 1) {
                        statisticsList.clear();
                        setStatisticsVipAdapter();
                    }
                    try {
                        JSONObject json = new JSONObject(text);
                        if (json.getInt("status") == 1 && json.getJSONObject("data").has("list")) {
                            statisticsVipBean = GsonUtils.JsonToBean(text, StatisticsVipBean.class);
                            statisticsList.addAll(statisticsVipBean.getData().getList());
                            setStatisticsVipAdapter();
                            statisticsPage++;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    memberStatisticsListView.onRefreshComplete();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void setStatisticsVipAdapter() {
        if (statisticsVipAdapter == null) {
            statisticsVipAdapter = new StatisticsVipAdapter(context, statisticsList);
            memberStatisticsListView.setAdapter(statisticsVipAdapter);
        } else {
            statisticsVipAdapter.notifyDataSetChanged();
        }
    }

    private void setEntries(ArrayList<PieEntry> entries, int type) {
        PieDataSet dataSet = new PieDataSet(entries, "");
//        PieDataSet dataSet = new PieDataSet(new ArrayList<>(), "");
        dataSet.setSliceSpace(3f);
        dataSet.setSelectionShift(12f);
        dataSet.setColors(colors);
        dataSet.setValueLinePart1OffsetPercentage(80.f);
        dataSet.setValueLinePart1Length(0.2f);
        dataSet.setValueLinePart2Length(0.8f);
        dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        dataSet.setValueLineColor(Color.WHITE);
        PieData data = new PieData(dataSet);
//        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(14f);
        data.setValueTextColor(ContextCompat.getColor(context, R.color.text_333));
        data.setValueFormatter(new TestDefaultValueFormatter());
        memberChart.setData(data);
        memberChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
                statisticsPage = 1;
                statisticsList.clear();
                setStatisticsVipAdapter();
                statisticsIndex = (int) h.getX();
                if (type == 1) {
                    getVipByBirth((int) h.getX());
                } else {
                    getVipByMonth(entries.get((int) h.getX()).getLabel());
                }
            }

            @Override
            public void onNothingSelected() {
            }
        });


        setLegend();
        memberChart.setExtraOffsets(16f, 16f, 16f, 16f);
        memberChart.invalidate();
    }

    private void setLegend() {
        Legend l = memberChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setWordWrapEnabled(true);
        l.setDrawInside(true);
        l.setXEntrySpace(0f);
        l.setYEntrySpace(0f);// 設置 tab 之間 Y 軸方向上的空白間距值
        l.setYOffset(0f);
        l.setEnabled(false);
        memberChart.invalidate();
    }


    private class TestDefaultValueFormatter extends PercentFormatter {
        private DecimalFormat mFormat;

        public TestDefaultValueFormatter() {
            mFormat = new DecimalFormat("###");//十進制格式
        }


        @Override
        public String getPieLabel(float value, PieEntry pieEntry) {
            if (Float.isNaN(value)) {
                return pieEntry.getLabel() +
                        "\r\n(" + 0 + "%)\r\n"
                        + 0 + getString(R.string.Per);
            } else {
                return pieEntry.getLabel() +
                        "\r\n(" + MathUtil.round(value, 2) + "%)\r\n"
                        + (int) MathUtil.round(value / 100 * allActivity, 2) + getString(R.string.Per);
            }
        }
    }

    private void changeStatistics(int type) {
        statisticsType = type;
        tvMemberBirthdayStatistics.setTextColor(ContextCompat.getColor(context, R.color.text_666));
        tvMemberActiveStatistics.setTextColor(ContextCompat.getColor(context, R.color.text_666));
        tvMemberSleepStatistics.setTextColor(ContextCompat.getColor(context, R.color.text_666));
        switch (type) {
            case 1:
                tvMemberBirthdayStatistics.setTextColor(ContextCompat.getColor(context, R.color.text_333));
                break;
            case 2:
                tvMemberActiveStatistics.setTextColor(ContextCompat.getColor(context, R.color.text_333));
                break;
            case 3:
                tvMemberSleepStatistics.setTextColor(ContextCompat.getColor(context, R.color.text_333));
                break;
            default:
                break;
        }
    }
}
